package com.huikeportal.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huikeportal.dao.BrandAnalysisMapper;
import com.huikeportal.dao.PosDataManagerMapper;
import com.huikeportal.model.BrandAnalysisGraphData;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.RankingData;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.ReportSiteDay;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteType;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.WordBook;
import com.huikeportal.service.BrandAnalysisService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;

/** 
 * 2015-10-12 
 * 品牌分析
 * author:focus
 */

@Service("BrandAnalysisService")
public class BrandAnalysisServiceImpl implements BrandAnalysisService {
	
	
	@Autowired
	private BrandAnalysisMapper brandAnalysisMapper;
	
	@Autowired
	private PosDataManagerMapper posDataManagerMapper;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;

	public HashMap<String, Object> getCalret(int type) {

		String calret = "";//统计的指标，客流，销额。。。
		String ziduan = "";//字段
		int isfloat = 0;//是否是浮点类型
		
		 switch (type)
         {
             case 1:
                 calret = "ifnull(sum(a.innum),0)";
                 ziduan = "innum";//客流量
                 break;
             case 2:
                 calret = "ifnull(sum(a.pos),0)";
                 ziduan = "pos";//销售额
                 isfloat = 1;
                 break;
             case 3:
                 calret = "round(ifnull(ifnull(sum(a.posnum),0)*100/ifnull(sum(a.innum),0),0),2)";
                 ziduan = "rateBags";//提袋率
                 isfloat = 1;
                 break;
             case 4:
                 calret = "round(ifnull(ifnull(sum(a.pos),0)/ifnull(sum(a.innum),0),0),2)";
                 ziduan = "posInnum";//客单价pos/innum
                 isfloat = 1;
                 break;
             case 5:
                 calret = "round(ifnull(ifnull(sum(a.pos),0)/ifnull(max(a.area),0),0),2)";
                 ziduan = "posArea";//坪效	pos/area
                 isfloat = 1;
                 break;
             case 6:
                 calret = "ifnull(sum(a.jkl),0)";
                 ziduan = "jkl";//集客力
                 break;
                 default:
                calret = "ifnull(sum(a.innum),0)";
                ziduan = "innum";
                break;	 
         }
		 HashMap<String,Object> map=new HashMap<String,Object>();
		 map.put("calret", calret);
		 map.put("ziduan", ziduan);
		 map.put("isfloat", isfloat);
		 
		return map;
		
	
	}

	public List<String> getDatesBetweenTwoDate(String begin, String end) {

    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date beginDate =null;	
    	Date endDate =null;
    	try {
			beginDate = sdf.parse(begin);
			endDate = sdf.parse(end);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        List<String> lDate = new ArrayList<String>();  
        lDate.add(sdf.format(beginDate));// 把开始时间加入集合  
        Calendar cal = Calendar.getInstance();  
        // 使用给定的 Date 设置此 Calendar 的时间  
        cal.setTime(beginDate);  
        boolean bContinue = true;  
        while (bContinue) {  
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量  
            cal.add(Calendar.DAY_OF_MONTH, 1);  
            // 测试此日期是否在指定日期之后  
            if (endDate.after(cal.getTime())) {  
                lDate.add(sdf.format(cal.getTime()));  
            } else {  
                break;  
            }  
        }  
        lDate.add(sdf.format(endDate));// 把结束时间加入集合  
        return lDate;  
    
	}
	
	/**
     * 根据id查询平牌中文名称
     * @param str
     * @return
     */
	public String getSiteName(String str){
		String brandName=brandAnalysisMapper.getBrandName(str);
		return brandName;
		
	}
	
	
	/**
     * 根据id查询平牌中文名称
     * @param str
     * @return
     */
	public String getbrandName(String str){
		String brandName=brandAnalysisMapper.getBrandNameById(str);
		return brandName;
	}
	
	public HashMap<String, Object> getPaihangGraphData(HashMap<String, Object> map)
	throws Exception {
		Map<String,List<BrandAnalysisGraphData>> dataMap = new HashMap<String,List<BrandAnalysisGraphData>>();
		
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String type="";
		if(map.get("type")!=null && !map.get("type").toString().equals("")){
			type=map.get("type").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		HashMap<String,Object> typeMap =getCalret(Integer.parseInt(type));
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		pramMap.put("calret", typeMap.get("calret"));
		pramMap.put("ziduan", typeMap.get("ziduan"));
		pramMap.put("siteId", siteId);
		HashMap<String, Object> pramdata = new HashMap<String, Object>();
		List<BrandAnalysisGraphData> dataList = brandAnalysisMapper.getBrandPaihangDataOfSites(pramMap);
		pramdata.put("dataList", dataList);
		return pramdata;
	}
	
	
	
	public List<HashMap<String, Object>> getScatterGraphData(HashMap<String, Object> map)
	throws Exception {
		Map<String,List<BrandAnalysisGraphData>> dataMap = new HashMap<String,List<BrandAnalysisGraphData>>();
		
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String type="";
		if(map.get("type")!=null && !map.get("type").toString().equals("")){
			type=map.get("type").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		String brandId="";
		if(map.get("brandId")!=null && !map.get("brandId").toString().equals("")){
			brandId=map.get("brandId").toString();
		}
		if(brandId.startsWith(",")){
			brandId=brandId.substring(1);
		}
		String[] brandIds = brandId.split(",");
		
		List<HashMap<String, Object>> retList = new ArrayList<HashMap<String, Object>>();
		HashMap<String,Object> typeMap =getCalret(Integer.parseInt(type));
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		pramMap.put("calret", typeMap.get("calret"));
		pramMap.put("ziduan", typeMap.get("ziduan"));
		pramMap.put("siteId", siteId);
		for(String brand : brandIds){
			HashMap<String, Object> pramdata = new HashMap<String, Object>();
			pramMap.put("brand", brand);
			List<BrandAnalysisGraphData> dataList = brandAnalysisMapper.getScatterGraphData(pramMap);
			String brandName = getbrandName(brand);
			pramdata.put("brandName", brandName);
			pramdata.put("brandId", brand);
			pramdata.put("dataList", dataList);			
			retList.add(pramdata);
		}
		return retList;
	}
	
	

	public List<HashMap<String, Object>> getGraphData(HashMap<String, Object> map)
			throws Exception {
		Map<String,List<BrandAnalysisGraphData>> dataMap = new HashMap<String,List<BrandAnalysisGraphData>>();
		
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String type="";
		if(map.get("type")!=null && !map.get("type").toString().equals("")){
			type=map.get("type").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		String brandId="";
		if(map.get("brandId")!=null && !map.get("brandId").toString().equals("")){
			brandId=map.get("brandId").toString();
		}
		if(brandId.startsWith(",")){
			brandId=brandId.substring(1);
		}
		String[] brandIds = brandId.split(",");

		List<HashMap<String, Object>> retList = new ArrayList<HashMap<String, Object>>();
		HashMap<String,Object> typeMap =getCalret(Integer.parseInt(type));
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		pramMap.put("calret", typeMap.get("calret"));
		pramMap.put("ziduan", typeMap.get("ziduan"));
		pramMap.put("siteId", siteId);
		for(String brand : brandIds){
			HashMap<String, Object> pramdata = new HashMap<String, Object>();
			pramMap.put("brand", brand);
			List<BrandAnalysisGraphData> dataList = brandAnalysisMapper.getBrandGraphDataOfSites(pramMap);
			//和应该有的日期对比，如果该日期没有数据设置为空，添加到list
			List<String> listDate=(List<String>)pramMap.get("Betweens");
			if(dataList.size()!=listDate.size()){
				for (int da=0;da<listDate.size();da++){
					Boolean flg=false;
					for(int rep=0;rep< dataList.size();rep++){
						if(listDate.get(da).equals(dataList.get(rep).getDatatime())){
							flg=true;
						}
					}
					if(flg){
						continue;
					}else{
						BrandAnalysisGraphData randAnalysisGraphData=new BrandAnalysisGraphData();
						randAnalysisGraphData.setDatatime(listDate.get(da));
						randAnalysisGraphData.init();
						dataList.add(da, randAnalysisGraphData);
					}
				}
			}
			String brandName = getbrandName(brand);
			pramdata.put("brandName", brandName);
			pramdata.put("brandId", brand);
			pramdata.put("dataList", dataList);
			pramdata.put("listDate",listDate);
			
			retList.add(pramdata);
		}
		return retList;
	/**
	 
//		List<String> brandNames = new ArrayList<String>();
//		UserInfo userInfo = null;
//		if(map.get("userInfo")!=null){
//			userInfo = (UserInfo)map.get("userInfo");
//		}
		
//		List<SiteAllInfo> allPermitSiteList = getAllPermitSitesList(userInfo);
		HashMap<SiteAllInfo,List<BrandAnalysisGraphData>> siteDataMap = new HashMap<SiteAllInfo,List<BrandAnalysisGraphData>>();
		
		for(int i=0,len=allPermitSiteList.size();i<len;i++){
			SiteAllInfo info = allPermitSiteList.get(i);
			for(String brandName : brandNames){
				if(info.getBrand()!=null && brandName.endsWith(info.getBrand())){
					List<BrandAnalysisGraphData> dataList = new ArrayList<BrandAnalysisGraphData>();
					pramMap.put("siteId", info.getSiteid());
					dataList = brandAnalysisMapper.getBrandGraphData(pramMap);
					//和应该有的日期对比，如果该日期没有数据设置为空，添加到list
					List<String> listDate=(List<String>)pramMap.get("Betweens");
					if(dataList.size()!=listDate.size()){
						for (int da=0;da<listDate.size();da++){
							Boolean flg=false;
							for(int rep=0;rep< dataList.size();rep++){
								if(listDate.get(da).equals(dataList.get(rep).getDatatime())){
									flg=true;
								}
							}
							if(flg){
								continue;
							}else{
								BrandAnalysisGraphData randAnalysisGraphData=new BrandAnalysisGraphData();
								randAnalysisGraphData.setDatatime(listDate.get(da));
								randAnalysisGraphData.setInnum(0);
								randAnalysisGraphData.setPos("0");
								dataList.add(da, randAnalysisGraphData);
							}
						}
					}
					
					siteDataMap.put(info,dataList);
					
				}
			}
		}
		
		for(Map.Entry<SiteAllInfo, List<BrandAnalysisGraphData>> entry : siteDataMap.entrySet()){
			SiteAllInfo key = entry.getKey();
			if(brandNames.contains(key.getBrand())){
				dataMap.put(key.getBrand(), entry.getValue());
			}
		}
		
		* 	
	 */
	}
	
	// 获取该用户所拥有的所有的店铺权限
	private List<SiteAllInfo> getAllPermitSitesList(UserInfo userInfo) throws Exception{
		
		// lowPermission < 300 的是广场以上的权限
		List<SiteAllInfo> permitSiteList = getSitesByUser(userInfo);
		int lowPermission = getLowPermission(permitSiteList);
		if(lowPermission < 300){
			List<SiteAllInfo> allGcList = getAllGcList(permitSiteList);
			List<SiteAllInfo> allSiteList = getAllSiteList(allGcList);
			allSiteList.addAll(allGcList);
			return allSiteList;
		}else{
			return getAllSiteList(permitSiteList);
		}
	}
	
	public List<SiteAllInfo> getSitesByUser(UserInfo userInfo) throws Exception {
		return brandAnalysisMapper.getSitesByUser(userInfo);
	}
	
	
	public int getLowPermission(List<SiteAllInfo> siteList){
		int permission = 0;
		for(int i=0,len = siteList.size();i<len;i++){
			if(siteList.get(i).getType()!= null){
				int currentPermission = siteList.get(i).getType();
				permission = permission < currentPermission ? currentPermission : permission;
			}
		}
		
		return permission;
	}
	
	public List<SiteAllInfo> getAllGcList(List<SiteAllInfo> siteList) throws Exception {
		List<SiteAllInfo> allGcList = new ArrayList<SiteAllInfo>();
		for(int i=0,len = siteList.size(); i<len; i++){
			SiteAllInfo temp = siteList.get(i);
			int type = temp.getType();
			if(type == 0){
				List<SiteAllInfo> jtList = posDataManagerMapper.getAllJtSites(temp);
				for(int j=0,length=jtList.size();j<length;j++){
					SiteAllInfo current = jtList.get(j);
					List<SiteAllInfo> gcList = posDataManagerMapper.getAllGcSitesByJt(current);
					allGcList.addAll(gcList);
				}
			}else if(type == 100){
				List<SiteAllInfo> gcList = posDataManagerMapper.getAllGcSitesByJt(temp);
				allGcList.addAll(gcList);
			}else if(type == 200){
				List<SiteAllInfo> gcList = posDataManagerMapper.getAllGcSitesByDy(temp);
				allGcList.addAll(gcList);
			}
		}
		return allGcList;
	}
	
	public List<SiteType> getSiteTypes(String para) throws Exception{
		List<WordBook> wordBooks = posDataManagerMapper.getSiteTypes(para);
		List<SiteType> siteTypes = new ArrayList<SiteType>();
		for(int i=0,len=wordBooks.size();i<len;i++){
			SiteType siteType = new SiteType();
			WordBook book = wordBooks.get(i);
			if(book != null){
				String[] word = book.getDicValue().split("\\|");
				siteType.setSiteTypeName(word[0]);
				//siteType.setSiteTypeId(word[1]);
			}
			siteTypes.add(siteType);
		}
		return siteTypes;
	}
	
	public List<SiteAllInfo> getAllSiteList(List<SiteAllInfo> siteList) throws Exception{
		List<SiteAllInfo> allSiteList = new ArrayList<SiteAllInfo>();
		for(int i=0,len=siteList.size();i<len;i++){
			SiteAllInfo temp = siteList.get(i);
			List<SiteAllInfo> tempList = posDataManagerMapper.getAllSitesByGc(temp);
			allSiteList.addAll(tempList);
		}
		
		allSiteList.addAll(siteList);
		return allSiteList;
	}
	
	public String getSitePermitAreaStr(List<SiteAllInfo> sitePermitList){
		StringBuffer buffer = new StringBuffer();
		for(int i=0,len=sitePermitList.size();i<len;i++){
			SiteAllInfo temp = sitePermitList.get(i);
			buffer.append(temp.getSiteid());
			buffer.append(",");
		}
		return buffer.toString();
	}
	
	
	/**
	 * 根据日期类型，时间段得出图表查询的参数值
	 * @param timeType_table
	 * @param timeType
	 * @param from
	 * @param to
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("deprecation")
	public HashMap<String, Object> getparam(String timeType_table,String timeType,String from,String to) throws ParseException{
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		
		//根据日周月年查询不同的报表
		if(timeType_table.equals("day")){
			resultMap.put("timeType_table", "day");
			//根据timeType计算查询几天的数据
			if(timeType.equals("0")){
				Date dateFrom= sf.parse(from);
				Date dateTo= sf.parse(to);
				resultMap.put("startDate",sf.format(dateFrom));
				resultMap.put("endDate", sf.format(dateTo));
			}else if(timeType.equals("7")){
				Date date=new Date();
				String endDate=sf.format(date);
				date.setDate(date.getDate()-7);
				String startDate=sf.format(date);
				resultMap.put("startDate", startDate);
				resultMap.put("endDate", endDate);
			}else if(timeType.equals("14")){
				Date date=new Date();
				String endDate=sf.format(date);
				date.setDate(date.getDate()-14);
				String startDate=sf.format(date);
				resultMap.put("startDate", startDate);
				resultMap.put("endDate", endDate);
				
			}else if(timeType.equals("30")){
				Date date=new Date();
				String endDate=sf.format(date);
				date.setDate(date.getDate()-30);
				String startDate=sf.format(date);
				resultMap.put("startDate", startDate);
				resultMap.put("endDate", endDate);
			}else if(timeType.equals("1")){
				resultMap.put("startDate",sf.format(new Date()));
				resultMap.put("endDate", sf.format(new Date()));
			}
			//根据开始时间结束时间算出时间段
			List<String> listDate=getDatesBetweenTwoDate(resultMap.get("startDate").toString(),resultMap.get("endDate").toString());
			resultMap.put("Betweens", listDate);
		}
		
		return resultMap;
	}
	
	
	public Map<String,Double> getRankingData(HashMap<String,Object> map) throws Exception{
		//获取时间
		String timeType="";
		if(map.get("timeType")!=null && map.get("timeType").toString()!=""){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && map.get("timeType_table").toString()!=""){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && map.get("startDate").toString()!=""){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && map.get("endDate").toString()!=""){
			to=map.get("endDate").toString();
		}
		UserInfo userInfo=null;
		if(map.get("userInfo")!=null){
			userInfo=(UserInfo) map.get("userInfo");
		}
		
		//获取要查询的指标
		int type=Integer.valueOf( map.get("type").toString());
		//根据指标拼接要查询的字段
		HashMap<String, Object> calretMap=getCalret(type);
		
		List<SiteAllInfo> allPermitSiteList = getAllPermitSitesList(userInfo);
		
		HashMap<SiteAllInfo,List<BrandAnalysisGraphData>> siteData = new HashMap<SiteAllInfo,List<BrandAnalysisGraphData>>();
		for(int i=0,len=allPermitSiteList.size();i<len;i++){
			SiteAllInfo info = allPermitSiteList.get(i);
			if(info.getBrand()!=null && !"".endsWith(info.getBrand())){
				HashMap<String,Object> paraMap = getparam(timeType_table,timeType,from,to);
				paraMap.put("siteId",info.getSiteid());
				paraMap.put("calret", calretMap.get("calret"));
				paraMap.put("ziduan", calretMap.get("ziduan"));
				List<BrandAnalysisGraphData> list = brandAnalysisMapper.getBrandGraphData(paraMap);
				siteData.put(info, list);
			}
		}
		
		Set<String> brandSet = new HashSet<String>();
		for(Entry<SiteAllInfo,List<BrandAnalysisGraphData>> entry : siteData.entrySet()){
			brandSet.add(entry.getKey().getBrand());
		}
		
		
		// 同一个品牌共有多上家店铺在做
		Map<String,Integer> brandSites = new HashMap<String,Integer>();
		for(String brand : brandSet){
			int siteNum = 0;
			for(Entry<SiteAllInfo,List<BrandAnalysisGraphData>> entry : siteData.entrySet()){
				if(entry.getKey().getBrand().endsWith(brand)){
					siteNum++;
				}
			}
			brandSites.put(brand, siteNum);
		}
		// 同一个品牌共有多少客流
		Map<String,Integer> brandPassengers = new HashMap<String,Integer>();
		// 同一个品牌共有多少销售额
		Map<String,Double> brandSales = new HashMap<String,Double>();
		
		if(type == 1){
			for(String brand : brandSet){
				int passengerNum = 0;
				for(Entry<SiteAllInfo,List<BrandAnalysisGraphData>> entry : siteData.entrySet()){
					if(entry.getKey().getBrand().endsWith(brand)){
						List<BrandAnalysisGraphData> list = entry.getValue();
						for(int j=0;j<list.size();j++){
							passengerNum+= list.get(j).getInnum();
						}
					}
				}
				brandPassengers.put(brand, passengerNum);
			}
		}else{
			for(String brand : brandSet){
				double sales = 0;
				for(Entry<SiteAllInfo,List<BrandAnalysisGraphData>> entry : siteData.entrySet()){
					if(entry.getKey().getBrand().endsWith(brand)){
						List<BrandAnalysisGraphData> list = entry.getValue();
						for(int j=0;j<list.size();j++){
							sales += Double.parseDouble(list.get(j).getPos());
						}
					}
				}
				brandSales.put(brand, sales);
			}
		}
		// 品牌对应的平均客流或平均销售额
		Map<String,Double> brandAvgPassenger = new HashMap<String,Double>();
		Map<String,Double> brandAvgSale = new HashMap<String,Double>();
		if(type==1){
			for(Entry<String,Integer> entry : brandSites.entrySet()){
				String brand = entry.getKey();
				for(Entry<String,Integer> en : brandPassengers.entrySet()){
					if(brand.endsWith(en.getKey())){
						double avgPassenger = en.getValue() / entry.getValue();
						brandAvgPassenger.put(brand, avgPassenger);
					}
				}
			}
		}else{
			for(Entry<String,Integer> entry : brandSites.entrySet()){
				String brand = entry.getKey();
				for(Entry<String,Double> en : brandSales.entrySet()){
					if(brand.endsWith(en.getKey())){
						double avgPassenger = en.getValue() / entry.getValue();
						brandAvgSale.put(brand, avgPassenger);
					}
				}
			}
		}
		
	 Map<String,Double> tempMap = new HashMap<String,Double>();
	 if(type==1){
		 tempMap = brandAvgPassenger;
	 }else{
		 tempMap = brandAvgSale;
	 }
	 
	 return sortMapByValue(tempMap);
	}


	public StringBuffer getRanking(HashMap<String, Object> map)
			throws Exception {
	StringBuffer buffer = new StringBuffer();
	 Map<String,Double> tempMap = getRankingData(map);
	 
	 int total =0;
	 double rule = 0;
	 
	 for(Entry<String,Double> entry : tempMap.entrySet()){
		 rule = entry.getValue();
		 break;
	 }
	 total = (int) (rule * 10 / 8);
	 
	 for(Entry<String,Double> entry :tempMap.entrySet()){

			float per=0;//数据条形图显示的比例
			//如果是第一个per=80，其他为num/total*100
			if(total==0){
				per=0;
			}else{
				per =(float) (entry.getValue()==null?0:entry.getValue() )* 100 / total;
			}
			
			String style = "";//显示5条其余的隐藏不显示，点击‘查看全部’显示全部。
			buffer.append("<div class='shujuhang' "+style+">");
			
//				buffer.append("<div class='shujupaixu'>"+i+"</div>");
				buffer.append("<div class='shujuname'>");
					
				buffer.append("<a >"+entry.getKey()+"</a>");
				buffer.append("</div>");
				
				buffer.append("<div class='shujutu'>");
					buffer.append("<div class='tiaoxingkuang'>");
						buffer.append("<div class='tiaoxing' style='width:"+per+"%'></div>");
					buffer.append("</div>");
				buffer.append("</div>");
				
				
//				按照type拼接需要计算什么字段 ，人流，销售额。。。
				buffer.append("<div class='shujudata'>"+entry.getValue()+"</div>");
				
				buffer.append("<div class='cleardiv'></div>");
			
			buffer.append("</div>");

	 }
		
		return buffer;
	}
	
	public Map<String,Double> sortMapByValue(Map<String,Double> oriMap){
		Map<String,Double> sortedMap = new LinkedHashMap<String, Double>();
		if(oriMap!=null && !oriMap.isEmpty()){
			List<Entry<String,Double>> entryList = new ArrayList<Entry<String,Double>>(oriMap.entrySet());
			Collections.sort(entryList,new Comparator<Entry<String,Double>>(){
				public int compare(Entry<String,Double> entry1,Entry<String,Double> entry2){
					double value1 = 0, value2 = 0;
					try{
						value1 = entry1.getValue();
						value2 = entry2.getValue();
					}catch(NumberFormatException e){
						value1 = 0;
						value2 = 0;
					}
					
					return ((int) -(value1-value2));
				}
			});
			
			
			Iterator<Entry<String,Double>> it = entryList.iterator();
			Entry<String,Double> tempEntry = null;
			while(it.hasNext()){
				tempEntry = it.next();
				sortedMap.put(tempEntry.getKey(), tempEntry.getValue());
			}
		}
		return sortedMap;
	}


	public MessageCommon hasSquareAuthor(UserInfo userInfo) throws Exception {
		MessageCommon message = new MessageCommon();
		// 数字越低，权限越高
		int highAuthor = 1000;
		List<SiteAllInfo> infos = brandAnalysisMapper.getSitesByUser(userInfo);
		for(int i=0,len=infos.size();i<len;i++){
			SiteAllInfo info = infos.get(i);
			if(info.getType() < highAuthor){
				highAuthor = info.getType();
			}
		}
		if(highAuthor > 300){
			message.setFlag(true);
			message.setMessage("没有权限");
			return message;
		}
		return message;
	}

	public StringBuffer getSelectedRanking(HashMap<String, Object> map)
			throws Exception {
		StringBuffer buffer = new StringBuffer();
		
		Map<String,Double> tempMap = getRankingData(map);
		
		String brandId="";
		if(map.get("brandId")!=null && !map.get("brandId").toString().equals("")){
			brandId=map.get("brandId").toString();
		}
		
		String[] brandIds = brandId.split(",");
		List<String> brandNames = new ArrayList<String>();
		for(String brand : brandIds){
			brandNames.add(brandAnalysisMapper.getBrandName(brand));
		}
		
		Iterator<Entry<String, Double>> it = tempMap.entrySet().iterator(); 
		while(it.hasNext()){
			Entry<String, Double> entry=it.next();
			if(!brandNames.contains(entry.getKey())){
				it.remove();
			}
		}

		 int total =0;
		 double rule = 0;
		 
		 for(Entry<String,Double> entry : tempMap.entrySet()){
			 rule = entry.getValue();
			 break;
		 }
		 total = (int) (rule * 10 / 8);
		 
		 for(Entry<String,Double> entry :tempMap.entrySet()){

				float per=0;//数据条形图显示的比例
				//如果是第一个per=80，其他为num/total*100
				
				if(total==0){
					per=0;
				}else{
					per =(float) (entry.getValue()==null?0:entry.getValue() )* 100 / total;
				}
				
				
				String style = "";//显示5条其余的隐藏不显示，点击‘查看全部’显示全部。
				buffer.append("<div class='shujuhang' "+style+">");
				
//					buffer.append("<div class='shujupaixu'>"+i+"</div>");
					buffer.append("<div class='shujuname'>");
						
					buffer.append("<a >"+entry.getKey()+"</a>");
					buffer.append("</div>");
					
					buffer.append("<div class='shujutu'>");
						buffer.append("<div class='tiaoxingkuang'>");
							buffer.append("<div class='tiaoxing' style='width:"+per+"%'></div>");
						buffer.append("</div>");
					buffer.append("</div>");
					
					
//					按照type拼接需要计算什么字段 ，人流，销售额。。。
					buffer.append("<div class='shujudata'>"+entry.getValue()+"</div>");
					
					buffer.append("<div class='cleardiv'></div>");
				
				buffer.append("</div>");

		 }
			
			return buffer;
	}

}
